package com.qlylkj.lbk.model.api

import com.forest.core.etx.versionCode
import com.forest.core.etx.versionName
import com.qlylkj.lbk.app.BaseApplication
import com.qlylkj.lbk.app.DebugConfig
import com.qlylkj.lbk.app.PreferenceHelper
import okhttp3.Cache
import okhttp3.CacheControl
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit


/**
 *    author : duanguosen
 *    date   : 2019/11/25
 *    desc   :
 */
object RetrofitHelper {

    /**
     * 正式环境
     */
    private const val REQUEST_BASE_URL = "http://47.103.75.211/qilinyunlian/"

    private const val MAX_CACHE_SIZE: Long = 1024 * 1024 * 50 // 50M 的缓存大小
    private const val CONNECT_TIMEOUT = 15L
    private const val READ_TIMEOUT = 15L
    private const val WRITE_TIMEOUT = 15L

    private var versionCode = BaseApplication.context.versionCode
    private var versionName = BaseApplication.context.versionName

    /**
     * create Retrofit
     */
    private fun createService(): Retrofit {
        // okHttpClientBuilder
        val okHttpClientBuilder = OkHttpClient().newBuilder().apply {
            val loggingInterceptor = HttpLoggingInterceptor()
            var level = HttpLoggingInterceptor.Level.NONE
            // 添加是否打开日志的标志
            if (DebugConfig.isOpenRetrofitLog()) {
                level = HttpLoggingInterceptor.Level.BODY
            }
            loggingInterceptor.level = level
            addInterceptor(loggingInterceptor)
            connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
            readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
            writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
            //设置 请求的缓存的大小跟位置
            val cacheFile = File(BaseApplication.context.cacheDir, "cache")
            val cache = Cache(cacheFile, MAX_CACHE_SIZE)
            cache(cache)
            addInterceptor {
                var request = it.request()
                request = if (!PreferenceHelper.hasNetwork) {
                    request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build()
                } else {
                    request.newBuilder()
                        .addHeader("appVersion", versionCode.toString())
                        .addHeader("packageName", versionName)
                        .addHeader("apiToken", PreferenceHelper.token)
                        .build()
                }
                var response = it.proceed(request)
                response = if (PreferenceHelper.hasNetwork) {
                    response.newBuilder()
                        .removeHeader("Pragma")
                        .header("Cache-Control", "public, max-age=${60 * 60}")// 有网络时 设置缓存超时时间1个小时
                        .build()
                } else {
                    response.newBuilder()
                        .removeHeader("Pragma")
                        .header(
                            "Cache-Control",
                            "public, only-if-cached, max-stale=${7 * 24 * 60 * 60}"
                        )// 无网络时，设置超时为1周
                        .build()
                }
                response
            }
        }
        return RetrofitBuild(
            url = REQUEST_BASE_URL,
            client = okHttpClientBuilder.build(),
            gsonFactory = GsonConverterFactory.create()
        ).retrofit
    }

    /**
     * get ServiceApi
     */
    fun <T> getService(service: Class<T>): T {
        return createService()
            .create(service)
    }

    /**
     * create retrofit build
     */
    class RetrofitBuild(
        url: String,
        client: OkHttpClient,
        gsonFactory: GsonConverterFactory
    ) {
        val retrofit: Retrofit = Retrofit.Builder().apply {
            baseUrl(url)
            client(client)
            addConverterFactory(gsonFactory)
        }.build()
    }

}